package com.mindmap.util;

import com.mindmap.model.MindMap;
import com.mindmap.model.Node;

import java.awt.*;

public class LayoutManager {
    private static final int NODE_WIDTH = 120;
    private static final int NODE_HEIGHT = 40;
    private static final int HORIZONTAL_GAP = 60;
    private static final int VERTICAL_GAP = 40;

    public static void autoLayout(MindMap mindMap) {
        if (mindMap == null || mindMap.getRoot() == null) return;

        Node root = mindMap.getRoot();
        root.setBounds(new Rectangle(400, 300, NODE_WIDTH, NODE_HEIGHT));

        int childCount = root.getChildren().size();
        int leftCount = childCount / 2;
        int rightCount = childCount - leftCount;

        // 左侧子节点
        layoutChildren(root, 0, leftCount, true);

        // 右侧子节点
        layoutChildren(root, leftCount, childCount, false);
    }

    public static void leftLayout(MindMap mindMap) {
        if (mindMap == null || mindMap.getRoot() == null) return;

        Node root = mindMap.getRoot();
        root.setBounds(new Rectangle(500, 300, NODE_WIDTH, NODE_HEIGHT));
        layoutChildren(root, 0, root.getChildren().size(), true);
    }

    public static void rightLayout(MindMap mindMap) {
        if (mindMap == null || mindMap.getRoot() == null) return;

        Node root = mindMap.getRoot();
        root.setBounds(new Rectangle(300, 300, NODE_WIDTH, NODE_HEIGHT));
        layoutChildren(root, 0, root.getChildren().size(), false);
    }

    private static void layoutChildren(Node parent, int start, int end, boolean left) {
        int childCount = end - start;
        if (childCount == 0) return;

        int parentX = parent.getBounds().x;
        int parentY = parent.getBounds().y;
        int parentHeight = parent.getBounds().height;

        int totalHeight = childCount * NODE_HEIGHT + (childCount - 1) * VERTICAL_GAP;
        int startY = parentY + parentHeight / 2 - totalHeight / 2;

        int x = left ? parentX - HORIZONTAL_GAP - NODE_WIDTH : parentX + parent.getBounds().width + HORIZONTAL_GAP;

        for (int i = start; i < end; i++) {
            Node child = parent.getChildren().get(i);
            child.setBounds(new Rectangle(x, startY, NODE_WIDTH, NODE_HEIGHT));
            startY += NODE_HEIGHT + VERTICAL_GAP;

            // 递归布局子节点
            if (!child.getChildren().isEmpty()) {
                layoutChildren(child, 0, child.getChildren().size(), left);
            }
        }
    }
}
